#include "XgThread.h"

#include "XgExceptions.h"

XgThread::XgThread()
{
	m_idThread = 0;
	m_queueThread = 0;
}

XgThread::~XgThread()
{

}

void XgThread::xg_run( LPDWORD ret )
{
	m_retThread = ret;
	*m_retThread = 0;
	onCreate.emit();
	run();
}

void XgThread::create()
{
	m_hThread = ::CreateThread(NULL, NULL, &xg_thread_proc, (void*)this, NULL, &m_idThread);
	if(!m_hThread)
	{
		throw XG_CANT_CREATE_THREAD_EX;
	}
	onCreate.wait();
}

void XgThread::exec()
{
	if( !m_queueThread )
	{
		m_queueThread = new XgMessagesQueue;
	}

	m_queueThread->peekMessage(NULL);
	onMessagesQueueCreate.emit();

	m_queueThread->exec();
}

void XgThread::postMessage(XgMessage* xgmsg)
{
	if(!::PostThreadMessage( m_idThread, XM_XGMESSAGE, (WPARAM)(void*)xgmsg, NULL ))
	{
		DWORD err = GetLastError();
		throw XG_CANT_POST_MESSAGE_EX;
	}
}

void XgThread::exit(DWORD ret = 0)
{
	*m_retThread = ret;
}

DWORD WINAPI xg_thread_proc( LPVOID lpParameter )
{
	XgThread* xgthread = (XgThread*)lpParameter;
	DWORD retThread;
	xgthread->xg_run(&retThread);
	return retThread;
}
